package by.grsu.epam.web.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import by.grsu.epam.service.entitiesservice.AccountService;

public class SubscriberInterceptor extends HandlerInterceptorAdapter {

	@Autowired
	private AccountService accountService;

	private String username;

	@Override
	public void postHandle(HttpServletRequest request, 
						   HttpServletResponse response, 
						   Object handler, 
						   ModelAndView modelAndView) throws Exception {

		Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}

		if (modelAndView != null && modelAndView.getModelMap() != null) {
			modelAndView.addObject("username", username);
			modelAndView.addObject("accounts", accountService.findBySubscriberUsername(username));
		}
	}

}
